﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Adams.Admin.Presentation
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class EnsureSslAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsSecureConnection)
            {
                // form new URL
                UriBuilder builder = new UriBuilder()
                {
                    Scheme = "https",
                    Host = filterContext.HttpContext.Request.Url.Host,
                    Path = filterContext.HttpContext.Request.Path,
                    Query = filterContext.HttpContext.Request.QueryString.ToString()
                };

                if (Shared.Config.GetAppSetting("SSLPort").ToInt() != 443)
                {
                    builder.Port = Shared.Config.GetAppSetting("SSLPort").ToInt();
                }

                filterContext.Result = new RedirectResult(builder.ToString());
            }
        }
    }
}